// 定义俄罗斯方块的形状和颜色
export type TetrominoType = 'I' | 'J' | 'L' | 'O' | 'S' | 'T' | 'Z';

export interface Tetromino {
  shape: number[][];
  type: TetrominoType;
  color: string;
}

export interface Position {
  x: number;
  y: number;
}

export interface GameState {
  board: (TetrominoType | null)[][];
  currentPiece: Tetromino;
  currentPosition: Position;
  nextPiece: Tetromino;
  score: number;
  level: number;
  lines: number;
  gameOver: boolean;
  isPaused: boolean;
}

// 定义所有俄罗斯方块的形状
export const TETROMINOES: Record<TetrominoType, Tetromino> = {
  I: {
    shape: [
      [0, 0, 0, 0],
      [1, 1, 1, 1],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
    ],
    type: 'I',
    color: 'bg-[#00f0f0]',
  },
  J: {
    shape: [
      [1, 0, 0],
      [1, 1, 1],
      [0, 0, 0],
    ],
    type: 'J',
    color: 'bg-[#0000f0]',
  },
  L: {
    shape: [
      [0, 0, 1],
      [1, 1, 1],
      [0, 0, 0],
    ],
    type: 'L',
    color: 'bg-[#f0a000]',
  },
  O: {
    shape: [
      [1, 1],
      [1, 1],
    ],
    type: 'O',
    color: 'bg-[#f0f000]',
  },
  S: {
    shape: [
      [0, 1, 1],
      [1, 1, 0],
      [0, 0, 0],
    ],
    type: 'S',
    color: 'bg-[#00f000]',
  },
  T: {
    shape: [
      [0, 1, 0],
      [1, 1, 1],
      [0, 0, 0],
    ],
    type: 'T',
    color: 'bg-[#a000f0]',
  },
  Z: {
    shape: [
      [1, 1, 0],
      [0, 1, 1],
      [0, 0, 0],
    ],
    type: 'Z',
    color: 'bg-[#f00000]',
  },
};

// 游戏常量
export const BOARD_WIDTH = 10;
export const BOARD_HEIGHT = 20;
export const POINTS = {
  SINGLE: 100,
  DOUBLE: 300,
  TRIPLE: 500,
  TETRIS: 800,
  SOFT_DROP: 1,
  HARD_DROP: 2,
};

// 创建空游戏板
export const createEmptyBoard = (): (TetrominoType | null)[][] => {
  return Array.from({ length: BOARD_HEIGHT }, () => 
    Array.from({ length: BOARD_WIDTH }, () => null)
  );
};

// 随机生成一个方块
export const randomTetromino = (): Tetromino => {
  const types = Object.keys(TETROMINOES) as TetrominoType[];
  const randomType = types[Math.floor(Math.random() * types.length)];
  return TETROMINOES[randomType];
};

// 检查碰撞
export const checkCollision = (
  board: (TetrominoType | null)[][],
  piece: Tetromino,
  position: Position
): boolean => {
  for (let y = 0; y < piece.shape.length; y++) {
    for (let x = 0; x < piece.shape[y].length; x++) {
      // 如果方块的这个部分是空的，跳过
      if (!piece.shape[y][x]) continue;
      
      // 计算在游戏板上的实际位置
      const boardX = position.x + x;
      const boardY = position.y + y;
      
      // 检查是否超出边界或与其他方块重叠
      if (
        boardX < 0 || 
        boardX >= BOARD_WIDTH || 
        boardY >= BOARD_HEIGHT ||
        (boardY >= 0 && board[boardY][boardX] !== null)
      ) {
        return true;
      }
    }
  }
  return false;
};

// 旋转方块
export const rotateTetromino = (piece: Tetromino): Tetromino => {
  // 创建一个新的旋转后的形状
  const rotatedShape = piece.shape.map((_, index) =>
    piece.shape.map(row => row[index]).reverse()
  );
  
  return {
    ...piece,
    shape: rotatedShape,
  };
};

// 清除完整的行
export const clearLines = (board: (TetrominoType | null)[][]): { newBoard: (TetrominoType | null)[][], linesCleared: number } => {
  let linesCleared = 0;
  const newBoard = [...board];
  
  for (let y = BOARD_HEIGHT - 1; y >= 0; y--) {
    // 检查这一行是否已满
    if (newBoard[y].every(cell => cell !== null)) {
      // 移除这一行
      newBoard.splice(y, 1);
      // 在顶部添加一个新的空行
      newBoard.unshift(Array(BOARD_WIDTH).fill(null));
      linesCleared++;
      // 因为我们删除了一行，所以需要重新检查当前行
      y++;
    }
  }
  
  return { newBoard, linesCleared };
};

// 计算新的分数
export const calculateScore = (lines: number, level: number): number => {
  switch (lines) {
    case 1:
      return POINTS.SINGLE * level;
    case 2:
      return POINTS.DOUBLE * level;
    case 3:
      return POINTS.TRIPLE * level;
    case 4:
      return POINTS.TETRIS * level;
    default:
      return 0;
  }
};

// 计算下落速度（毫秒）
export const calculateDropTime = (level: number): number => {
  return Math.max(100, 1000 - (level - 1) * 100);
};

// 计算新的等级
export const calculateLevel = (lines: number): number => {
  return Math.floor(lines / 10) + 1;
};

// 获取方块的阴影位置（预览落地位置）
export const getGhostPosition = (
  board: (TetrominoType | null)[][],
  piece: Tetromino,
  position: Position
): Position => {
  let ghostPosition = { ...position };
  
  while (!checkCollision(board, piece, { ...ghostPosition, y: ghostPosition.y + 1 })) {
    ghostPosition.y += 1;
  }
  
  return ghostPosition;
};